<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import { goMyFamily,getRouteParams } from "../../tools/go";
import {getFamily,getUserId} from "../../store"
import {createHousehold, getCommunitySelectList, getHouseholdById, updateHousehold} from "../../api/family/household"
import UniPopup from "../../uni_modules/uni-popup/components/uni-popup/uni-popup.vue";
import UniPopupDialog from "../../uni_modules/uni-popup/components/uni-popup-dialog/uni-popup-dialog.vue";
import UniPopupMessage from "../../uni_modules/uni-popup/components/uni-popup-message/uni-popup-message.vue";
import UniIcons from "../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import UniDataSelect from "../../uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
const ethnicList = ["汉族", "满族", "回族", "藏族", "维吾尔族", "其他"];
const ethnicIndex = ref(0);

const title = ref("添加租户")

let formData = reactive({
  id: 0,
  familyId: getFamily(),
  userId: 0,
  householdName: "",
  householdRmake: "",
  phone: "",
  cardNum: "",
  sex: true,
  ethnicGroup: "",
  birthDate: "",
  communilyId: 0,
  curReside: "",
  updateBy: getUserId(),
  updateTime: "",
});

const errors = reactive({
  householdName: "",
  phone: "",
  cardNum: "",
});

const messagePopup = ref();
const dialogPopup = ref();
const submitting = ref(false);

const popupConfig = reactive({
  type: "success",
  message: "",
});

const isFormValid = computed(() => {
  return (
      !errors.householdName &&
      !errors.phone &&
      !errors.cardNum &&
      formData.householdName &&
      formData.phone &&
      formData.cardNum
  );
});

const validateField = (field: string) => {
  switch (field) {
    case "householdName":
      if (!formData.householdName) {
        errors.householdName = "请输入户主姓名";
      } else if (
          formData.householdName.length < 2 ||
          formData.householdName.length > 20
      ) {
        errors.householdName = "户主姓名长度应在2-20个字符之间";
      } else {
        errors.householdName = "";
      }
      break;
    case "phone":
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!formData.phone) {
        errors.phone = "请输入手机号码";
      } else if (!phoneReg.test(formData.phone)) {
        errors.phone = "请输入正确的手机号码";
      } else {
        errors.phone = "";
      }
      break;
    case "cardNum":
      const cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!formData.cardNum) {
        errors.cardNum = "请输入身份证号";
      } else if (!cardReg.test(formData.cardNum)) {
        errors.cardNum = "请输入正确的身份证号";
      } else {
        errors.cardNum = "";
      }
      break;
  }
};

const onEthnicChange = (e: any) => {
  const index = e.detail.value;
  formData.ethnicGroup = ethnicList[index];
  ethnicIndex.value = index;
};

const onBirthDateChange = (e: any) => {
  formData.birthDate = e.detail.value;
};

const showMessage = (type: "success" | "error", message: string) => {
  popupConfig.type = type;
  popupConfig.message = message;
  messagePopup.value.open();
};

const handleSubmit = async () => {
  if (!isFormValid.value) return;

  createHousehold(formData).then((res) => {
    if (res.code === 200) {
      showMessage("success", "添加成功");
      goMyFamily()
    }
  })
};

const handSave = () => {
  updateHousehold(formData).then(res => {
    if (res.code === 200) {
      showMessage("success", "修改成功");
      goMyFamily()
    }
  })
}

const handleBack = () => {
  goMyFamily()
};

const confirmBack = () => {
  uni.navigateBack();
};

const cancelBack = () => {
  dialogPopup.value.close();
};




const communityPage = {
  page: 1,
  size: 10
}

const communityList = ref([])


const getCommunityList = () => {
  getCommunitySelectList(communityPage.page, communityPage.size).then((res) => {
      res.data["records"].forEach(item => {
        communityList.value.push({
          text: item.communityName,
          value: item.key
        })
      })

  });
};

const init = () =>{
  getCommunityList()
  let id = getRouteParams("id")
  if (id !== null) {
    title.value = "编辑租户"
    getHouseholdById(Number(id)).then(res => {
      formData.id = res.data.id
      formData.householdName = res.data.householdName
      formData.phone = res.data.phone
      formData.cardNum = res.data.cardNum
      formData.sex = res.data.sex === "男"
      formData.ethnicGroup = res.data.ethnicGroup
      formData.birthDate = res.data.birthDate
      formData.communilyId = res.data.communilyId
      formData.curReside = res.data.curReside
      formData.householdRmake = res.data.householdRmake
      formData.familyId = res.data.familyId
    })

  }

}
init()
</script>

<template>
  <view class="page">
    <view class="nav-bar">
      <uni-icons @click="handleBack" type="left" size="20" class="nav-back" />
      <text class="nav-title">{{title}}</text>
    </view>

    <scroll-view class="form-container" scroll-y>
      <view class="form-group">
        <view class="group-title">基本信息</view>

        <view class="form-item">
          <text class="label required">租户姓名</text>
          <input
              v-model="formData.householdName"
              class="input"
              :class="{'error': errors.householdName}"
              placeholder="请输入租户姓名"
              @input="validateField('householdName')"
          />
          <text v-if="errors.householdName" class="error-tip"
          >{{errors.householdName}}</text
          >
        </view>

        <view class="form-item">
          <text class="label required">手机号码</text>
          <input
              v-model="formData.phone"
              class="input"
              :class="{'error': errors.phone}"
              type="number"
              maxlength="11"
              placeholder="请输入手机号码"
              @input="validateField('phone')"
          />
          <text v-if="errors.phone" class="error-tip">{{errors.phone}}</text>
        </view>

        <view class="form-item">
          <text class="label required">身份证号</text>
          <input
              v-model="formData.cardNum"
              class="input"
              :class="{'error': errors.cardNum}"
              placeholder="请输入身份证号"
              @input="validateField('cardNum')"
          />
          <text v-if="errors.cardNum" class="error-tip"
          >{{errors.cardNum}}</text
          >
        </view>

        <view class="form-item">
          <text class="label required">性别</text>
          <view class="radio-group">
            <view class="radio-item" @click="formData.sex = true">
              <view class="radio" :class="{'checked': formData.sex}"></view>
              <text>男</text>
            </view>
            <view class="radio-item" @click="formData.sex = false">
              <view class="radio" :class="{'checked': !formData.sex}"></view>
              <text>女</text>
            </view>
          </view>
        </view>

        <view class="form-item">
          <text class="label">民族</text>
          <picker
              :value="ethnicIndex"
              :range="ethnicList"
              @change="onEthnicChange"
          >
            <view class="picker">
              {{formData.ethnicGroup || '请选择民族'}}
              <uni-icons type="right" size="16" class="picker-arrow" />
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">出生日期</text>
          <picker
              mode="date"
              :value="formData.birthDate"
              @change="onBirthDateChange"
          >
            <view class="picker">
              {{formData.birthDate || '请选择出生日期'}}
              <uni-icons type="right" size="16" class="picker-arrow" />
            </view>
          </picker>
        </view>
      </view>

      <view class="form-group">
        <view class="group-title">居住信息</view>

        <view class="form-item">
          <text class="label">社区ID</text>
          <uni-data-select
              v-model="formData.communilyId"
              :localdata="communityList"
              :placeholder="'请选择社区'"
          ></uni-data-select>
        </view>


        <view class="form-item">
          <text class="label">现居地址</text>
          <textarea
              v-model="formData.curReside"
              class="textarea"
              placeholder="请输入现居地址"
          />
        </view>

        <view class="form-item">
          <text class="label">备注</text>
          <textarea
              v-model="formData.householdRmake"
              class="textarea"
              placeholder="请输入备注信息"
          />
        </view>
      </view>
    </scroll-view>

    <view class="submit-bar">
      <button
          v-if="title === '编辑住户'"
          class="submit-btn"
          :disabled="!isFormValid || submitting"
          :loading="submitting"
          @click="handleSubmit"
      >
       添加
      </button>
      <button
          v-else
          class="submit-btn"
          :disabled="!isFormValid || submitting"
          :loading="submitting"
          @click="handSave"
      >
       保存
      </button>
    </view>

    <uni-popup ref="messagePopup" type="message">
      <uni-popup-message
          :type="popupConfig.type"
          :message="popupConfig.message"
          :duration="2000"
      />
    </uni-popup>

    <uni-popup ref="dialogPopup" type="dialog">
      <uni-popup-dialog
          type="warning"
          title="提示"
          content="是否放弃当前编辑的内容？"
          :duration="2000"
          @confirm="confirmBack"
          @close="cancelBack"
      />
    </uni-popup>
  </view>
</template>



<style scoped lang="scss">

.page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.nav-bar {
  position: relative;
  display: flex;
  align-items: center;
  height: 88rpx;
  background-color: #ffffff;
  padding: 0 30rpx;
  flex-shrink: 0;
}

.nav-back {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.form-container {
  flex: 1;
  overflow: auto;
  padding: 20rpx 0;
}

.form-group {
  margin-bottom: 20rpx;
  background-color: #ffffff;
  padding: 0 30rpx;
}

.group-title {
  font-size: 14px;
  color: #333333;
  font-weight: 500;
  padding: 30rpx 0;
}

.form-item {
  padding: 20rpx 0;
  border-top: 1px solid #f5f5f5;
}

.label {
  display: block;
  font-size: 14px;
  color: #333333;
  margin-bottom: 20rpx;
}

.required::after {
  content: "*";
  color: #ff4d4f;
  margin-left: 8rpx;
}

.input {
  height: 80rpx;
  border: 1px solid #e8e8e8;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 14px;
}

.input.error {
  border-color: #ff4d4f;
}

.error-tip {
  font-size: 12px;
  color: #ff4d4f;
  margin-top: 10rpx;
}

.radio-group {
  display: flex;
  gap: 60rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.radio {
  width: 40rpx;
  height: 40rpx;
  border: 1px solid #e8e8e8;
  border-radius: 50%;
  position: relative;
}

.radio.checked::after {
  content: "";
  position: absolute;
  width: 24rpx;
  height: 24rpx;
  background-color: #2979ff;
  border-radius: 50%;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.picker {
  height: 80rpx;
  border: 1px solid #e8e8e8;
  border-radius: 8rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
}

.picker-arrow {
  color: #999999;
}

.textarea {
  width: 100%;
  height: 160rpx;
  border: 1px solid #e8e8e8;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 14px;
}

.submit-bar {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  flex-shrink: 0;
}

.submit-btn {
  background-color: #2979ff;
  color: #ffffff;
  font-size: 16px;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
}

.submit-btn[disabled] {
  background-color: #cccccc;
}
</style>
